package common.util;

import common.config.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.codec.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具
 *
 * @author 米泽鹏
 * @since 2021-07-31 5:02 下午
 */

@Slf4j
public class EncryptionUtil {

	/**
	 * 校验密码是否正确
	 *
	 * @param password       前端传过来的密码
	 * @param hashedPassword 数据库中储存的加密过后的密码
	 * @param salt           盐值
	 * @return boolean 密码是否正确
	 */
	public static boolean isValidPassword(String password, String hashedPassword, String salt) {
		return hashedPassword.equalsIgnoreCase(encode(password, salt));
	}

	/**
	 * 通过SHA1对密码进行编码
	 *
	 * @param plaintext 明文
	 * @param salt      盐值
	 * @return 密文
	 */
	public static String encode(String plaintext, String salt) {
		String ciphertext;
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			if (salt != null) {
				digest.reset();
				digest.update(salt.getBytes());
			}
			byte[] hashed = digest.digest(plaintext.getBytes());
			for (int i = 0; i < Constants.HASH_ITERATIONS; ++i) {
				digest.reset();
				hashed = digest.digest(hashed);
			}
			ciphertext = new String(Hex.encode(hashed));
			return ciphertext;
		} catch (NoSuchAlgorithmException e) {
			log.error("加密异常:", e);
			throw new CustomException(e);
		}
	}

}
